import "./CesiumMap.css";
import { TOKEN, defaultOptions } from "./config";
import { GCJ02ToWGS84 } from "./CoordTransform";
import AroundPoint from "./AroundPoint.js";
import { useMapStore } from "@/stores/useMap";
const { setMarkerItem, setMarkerVisible } = useMapStore();
let baseUrl =
  import.meta.env.MODE == "development"
    ? "/gulou"
    : "https://zhyl.gulou.njapld.com:8081";

declare global {
  interface Window {
    Cesium: any;
  }
}
let Cesium = window.Cesium;

let initialHeading = 0;
// 步长
let step = 0.05;
class Controller {
  viewer: any;
  constructor() {
    if (window.Cesium) {
      window.Cesium.Ion.defaultAccessToken = TOKEN;
    }
  }
  createViewer(container, config) {
    Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(
      90,
      -20,
      110,
      90
    ); //西南东北，默认显示中国
    if (!this.viewer) {
      if (Cesium.defined(container)) {
        this.viewer = new Cesium.Viewer(container, {
          ...defaultOptions,
        });
      } else {
        let container: any = null;
        const ExistEl = document.getElementById("tao-map-view");
        if (!ExistEl) {
          container = document.createElement("div");
          container.className = `tao-map`;
          container.id = `tao-map-view`;
          document.body.appendChild(container);
        } else {
          container = ExistEl;
        }
        this.viewer = new Cesium.Viewer(container, {
          ...defaultOptions,
        });
      }
    }
    Cesium.ExperimentalFeatures.enableModelExperimental = true;
    var supportsImageRenderingPixelated =
      this.viewer.cesiumWidget._supportsImageRenderingPixelated;
    if (supportsImageRenderingPixelated) {
      var vtxf_dpr = window.devicePixelRatio;
      while (vtxf_dpr >= 2.0) {
        vtxf_dpr /= 2.0;
      }
      this.viewer.resolutionScale = vtxf_dpr;
    }
    // 添加3D建筑
    // this.viewer.scene.primitives.add(Cesium.createOsmBuildings())
    // this.viewer.scene.debugShowFramesPerSecond = true
    // this.viewer.scene.requestRenderMode = true
    //背景透明
    this.viewer.scene.backgroundColor = new Cesium.Color(0.0, 0.0, 0.0, 0.0);
    this.viewer.scene.undergroundMode = true; //隐藏地球
    this.viewer.scene.globe.translucency.enabled = true;
    //设置地平面
    this.viewer.scene.globe.depthTestAgainstTerrain = false;
    this.viewer.scene.fxaa = false;
    this.viewer.scene.postProcessStages.fxaa.enabled = true;
    //去除版权信息
    this.viewer.cesiumWidget.creditContainer.style.display = "none";
    // this.viewer.camera.flyTo({
    //   destination: Cesium.Cartesian3.fromDegrees(118.922105, 32.02699, 10000),
    //   orientation: {
    //     heading: Cesium.Math.toRadians(0),
    //     pitch: Cesium.Math.toRadians(-40),
    //     roll: Cesium.Math.toRadians(0),
    //   },
    // });
    // 禁止相机进入地下
    // this.viewer.clock.onTick.addEventListener(() => {
    //   this.viewer.scene.screenSpaceCameraController.minimumZoomDistance = 120;
    // });

    // this.OperationHabit()
    this.addImageryProvider();
    this.clearOpenLight(this.viewer);
    // this.CustomShaderBg();
    this.modifyMap(this.viewer);

    // setInterval(
    //   this.rotateCamera(this.viewer, {
    //     lng: "118.796624",
    //     lat: "32.059344",
    //   }),
    //   1000
    // );
  }

  modifyMap(viewer) {
    // 获取地图影像图层
    let baseLayer = viewer.imageryLayers.get(0);
    //设置2个变量，用来判断是否进行颜色的翻转和过滤
    baseLayer.invertColor = true;

    baseLayer.filterRGB = [3, 10, 21]; //[255,255,255] = > [0,50,100]
    //   更改底图着色器的代码
    const baseFragmentShader =
      viewer.scene.globe._surfaceShaderSet.baseFragmentShaderSource.sources;
    // console.log(baseFragmentShader);

    // 循环修改着色器
    for (let i = 0; i < baseFragmentShader.length; i++) {
      // console.log(baseFragmentShader[i]);
      const strS =
        "color = czm_saturation(color, textureSaturation);\n#endif\n";
      let strT = "color = czm_saturation(color, textureSaturation);\n#endif\n";
      if (baseLayer.invertColor) {
        strT += `
        color.r = 1.0 - color.r;
        color.g = 1.0 - color.g;
        color.b = 1.0 - color.b;
      `;
      }
      if (baseLayer.filterRGB) {
        strT += `
        color.r = color.r*${baseLayer.filterRGB[0]}.0/255.0;
        color.g = color.g*${baseLayer.filterRGB[1]}.0/255.0;
        color.b = color.b*${baseLayer.filterRGB[2]}.0/255.0;
      `;
      }

      baseFragmentShader[i] = baseFragmentShader[i].replace(strS, strT);
    }
  }
  // 置操作习惯,更换中键和右键
  OperationHabit() {
    this.viewer.scene.screenSpaceCameraController.tiltEventTypes = [
      Cesium.CameraEventType.RIGHT_DRAG,
      Cesium.CameraEventType.PINCH,
      {
        eventType: Cesium.CameraEventType.LEFT_DRAG,
        modifier: Cesium.KeyboardEventModifier.CTRL,
      },
      {
        eventType: Cesium.CameraEventType.RIGHT_DRAG,
        modifier: Cesium.KeyboardEventModifier.CTRL,
      },
    ];

    this.viewer.scene.screenSpaceCameraController.zoomEventTypes = [
      Cesium.CameraEventType.MIDDLE_DRAG,
      Cesium.CameraEventType.WHEEL,
      Cesium.CameraEventType.PINCH,
    ];
    this.viewer.scene.screenSpaceCameraController.rotateEventTypes = [
      Cesium.CameraEventType.LEFT_DRAG,
    ];
  }
  // 关闭光照效果
  clearOpenLight(viewer) {
    viewer.scene.globe.enableLighting = false;
    viewer.shadows = false;
    viewer.terrainShadows = Cesium.ShadowMode.DISABLED;
  }

  /**添加图层 */
  addImageryProvider() {
    const layerMap = {
      tdt: () => {
        const tdt_tk = "d470145fd294d79472f13d76063518ea"; //一天只能请求一万次啊
        //在线天地图影像服务地址(墨卡托投影)
        var TDT_IMG_W =
          "http://{s}.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0" +
          "&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}" +
          "&style=default&format=tiles&tk=" +
          tdt_tk;
        // //在线天地图矢量地图服务(墨卡托投影)
        // var TDT_VEC_W =
        // 	'http://{s}.tianditu.gov.cn/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
        // 	'&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
        // 	'&style=default&format=tiles&tk=' +
        // 	tdt_tk
        // //在线天地图影像中文标记服务(墨卡托投影)
        // var TDT_CIA_W =
        // 	'http://{s}.tianditu.gov.cn/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
        // 	'&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
        // 	'&style=default.jpg&tk=' +
        // 	tdt_tk
        // //在线天地图矢量中文标记服务(墨卡托投影)
        // var TDT_CVA_W =
        // 	'http://{s}.tianditu.gov.cn/cva_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
        // 	'&LAYER=cva&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
        // 	'&style=default.jpg&tk=' +
        // 	tdt_tk
        let Img = new Cesium.WebMapTileServiceImageryProvider({
          url: TDT_IMG_W, //url地址，换影像还是矢量，随便你喜欢
          layer: "img_w", //WMTS请求的层名称
          style: "default", //WMTS请求的样式名称
          format: "tiles", //MIME类型，用于从服务器检索图像
          tileMatrixSetID: "GoogleMapsCompatible", //	用于WMTS请求的TileMatrixSet的标识符
          subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"], //天地图8个服务器
          minimumLevel: 0, //最小层级
          maximumLevel: 18, //最大层级
        });
        // this.viewer.imageryLayers.addImageryProvider(Img) //添加到cesium图层上
        // let cia = new Cesium.WebMapTileServiceImageryProvider({
        // 	//调用中文注记服务
        // 	url: TDT_CVA_W,
        // 	layer: 'cia_w',
        // 	style: 'default',
        // 	format: 'tiles',
        // 	tileMatrixSetID: 'GoogleMapsCompatible',
        // 	subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'], //天地图8个服务器
        // 	minimumLevel: 0,
        // 	maximumLevel: 18,
        // })
        // this.viewer.imageryLayers.addImageryProvider(cia) //添加到cesium图层上
        this.viewer.imageryLayers.addImageryProvider(Img); //添加到cesium图层上
      },
      amap: () => {
        const layer_img = new Cesium.UrlTemplateImageryProvider({
          // url: 'http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', // 矢量图
          url: "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}", //高德影像图
          minimumLevel: 3,
          maximumLevel: 18,
        });

        // 高德标记图
        const layer_cva = new Cesium.UrlTemplateImageryProvider({
          url: "http://webst02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8",
          minimumLevel: 3,
          maximumLevel: 18,
        });
        this.viewer.imageryLayers.addImageryProvider(layer_img);
        // this.viewer.imageryLayers.addImageryProvider(layer_cva)
      },
    };
    // layerMap.tdt()
    layerMap.amap();
    // 没有影像图层时地球的底色
    // this.viewer.scene.globe.baseColor = Cesium.Color.BLACK
  }
  CustomShaderBg() {
    const customShader = new Cesium.CustomShader({
      //不考虑光照模型
      lightingModel: Cesium.LightingModel.UNLIT,
      //设置变量，由顶点着色器传递给片元着色器
      varyings: {
        v_normalMC: Cesium.VaryingType.VEC3,
        v_st: Cesium.VaryingType.VEC3,
      },
      //外部传给顶点着色器或者片元着色器
      uniforms: {
        u_texture: {
          value: new Cesium.TextureUniform({
            url: "https://aplid-51.oss-cn-hangzhou.aliyuncs.com/1704456410179_a936fa09.png",
          }),
          type: Cesium.UniformType.SAMPLER_2D,
        },
        u_texture1: {
          value: new Cesium.TextureUniform({
            url: "https://aplid-51.oss-cn-hangzhou.aliyuncs.com/1704456410179_a936fa09.png",
          }),
          type: Cesium.UniformType.SAMPLER_2D,
        },
      },
      //贴纹理
      //顶点着色器
      //将法向量从顶点着色器设置变量传给片元着色器
      vertexShaderText: `
            void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) {
                  v_normalMC = vsInput.attributes.normalMC;
                  v_st=vsInput.attributes.positionMC ;   
            }`,
      //片元着色器
      fragmentShaderText: `
      
           void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
              vec3 positionMC = fsInput.attributes.positionMC;
              //这里是设置要贴图的图片的尺寸，设置小了会重复
              float width = 37.0;
              float height = 40.0;
              vec3 rgb;
              //这是是设置了屋顶的颜色，当和法向量平行时，就是屋顶，这里设置0.95，相当于垂直，建筑物四周开始贴图
              if (dot(vec3(0.0, 1.0, 0.0), v_normalMC) > 0.95) {
                material.diffuse = vec3(1.0, 0.0, 0.0);
              } else {
                float textureX = 0.0;
                float dotYAxis = dot(vec3(0.0, 0.0, 1.0), v_normalMC);
                // cos(45deg) 约等于 0.71，这里是建筑物四周的向量与法向量会大于四十五度夹角
                if (dotYAxis > 0.71 || dotYAxis < -0.71) {
                //x代表的是前后面
                  textureX = mod(positionMC.x, width) / width;
                } else {
                //z代表的是左右面
                  textureX = mod(positionMC.z, width) / width;
                }
                float textureY = mod(positionMC.y, height) / height;
                //我这里是根据建筑物高度贴了两张不同的图片
                if (positionMC.y > 30.0) {
                   rgb = texture2D(u_texture1, vec2(textureX, textureY)).rgb;       
                } else {
                   rgb = texture2D(u_texture, vec2(textureX, textureY)).rgb;
                }
                material.diffuse = rgb;
              }
          }`,
    });

    return customShader;
  }

  CustomShaderLine() {
    const customShader = new Cesium.CustomShader({
      //不考虑光照模型
      lightingModel: Cesium.LightingModel.UNLIT,
      //修改片元着色器
      fragmentShaderText: `
    void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
            float _baseHeight = 0.0; // 物体的基础高度，需要修改成一个合适的建筑基础高度
            float _heightRange = 60.0; // 高亮的范围(_baseHeight ~ _baseHeight + _      heightRange) 默认是 0-60米
            float _glowRange = 300.0; // 光环的移动范围(高度)
        float vtxf_height = fsInput.attributes.positionMC.z-_baseHeight;
        float vtxf_a11 = fract(czm_frameNumber / 120.0) * 3.14159265 * 2.0;
        float vtxf_a12 = vtxf_height / _heightRange + sin(vtxf_a11) * 0.1;
        material.diffuse*= vec3(vtxf_a12, vtxf_a12, vtxf_a12);
        float vtxf_a13 = fract(czm_frameNumber / 360.0);
        float vtxf_h = clamp(vtxf_height / _glowRange, 0.0, 1.0);
        vtxf_a13 = abs(vtxf_a13 - 0.5) * 2.0;
        float vtxf_diff = step(0.005, abs(vtxf_h - vtxf_a13));
        material.diffuse += material.diffuse * (1.0 - vtxf_diff);
    }
    `,
    });
    return customShader;
  }

  add3DTiles() {
    let tileset = this.viewer.scene.primitives.add(
      new Cesium.Cesium3DTileset({
        url: `${baseUrl}/apld-tiles/gulou_model/tileset.json`,
        skipLevelOfDetail: true,
        baseScreenSpaceError: 1024,
        skipScreenSpaceErrorFactor: 16,
        skipLevels: 1,
        immediatelyLoadDesiredLevelOfDetail: false,
        loadSiblings: false,
        cullWithChildrenBounds: true,
      })
    );
    tileset.tileLoad.addEventListener((tileset) => {
      // console.log(tileset, '模型加载了')
    });

    tileset.readyPromise.then((tileset) => {
      let styleReload = new Cesium.Cesium3DTileStyle({
        color: {
          // conditions: [['true', 'rgba(255, 255, 255, 1)']],
          conditions: [["true", "rgba(0, 255, 139, 1)"]],
        },
      });
      tileset.style = styleReload;
      const heightOffset = 0; // 高度偏差，正数为向上偏，负数为向下偏，根据真实的模型位置不断进行调整
      let boundingSphere = tileset.boundingSphere; // 获取边界
      var cartographic = Cesium.Cartographic.fromCartesian(
        boundingSphere.center
      ); // 计算中心点位置
      var lng = Cesium.Math.toDegrees(cartographic.longitude); //使用经纬度和弧度的转换，将WGS84弧度坐标系转换到目标值，弧度转度
      var lat = Cesium.Math.toDegrees(cartographic.latitude);
      //计算中心点位置的地表坐标
      var surface = Cesium.Cartesian3.fromDegrees(lng, lat, 0);
      //偏移后的坐标
      var offset = Cesium.Cartesian3.fromDegrees(lng, lat, heightOffset);
      var translation = Cesium.Cartesian3.subtract(
        offset,
        surface,
        new Cesium.Cartesian3()
      );
      tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
      //将定义好的着色器作用域建筑tilesets
      tileset.customShader = this.CustomShaderLine();
      this.viewer.zoomTo(tileset);
    });
  }
  rotateCamera(cesiumView, cameras) {
    var pitch = Cesium.Math.toRadians(-25);
    // 给定飞行一周所需时间，比如10s, 那么每秒转动度数
    var angle = 360 / 100;
    // 给定相机距离点多少距离飞行，这里取值为5000m
    var distance = 280;
    var startTime = Cesium.JulianDate.fromDate(new Date());
    var stopTime = Cesium.JulianDate.addSeconds(
      startTime,
      10,
      new Cesium.JulianDate()
    );
    cesiumView.clock.startTime = startTime.clone(); // 开始时间
    cesiumView.clock.stopTime = stopTime.clone(); // 结速时间
    cesiumView.clock.currentTime = startTime.clone(); // 当前时间
    cesiumView.clock.clockRange = Cesium.ClockRange.CLAMPED; // 行为方式
    cesiumView.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK; // 时钟设置为当前系统时间; 忽略所有其他设置。
    // 相机的当前heading
    var initialHeading = cesiumView.camera.heading;
    var Exection = () => {
      // 当前已经过去的时间，单位s
      var delTime = Cesium.JulianDate.secondsDifference(
        cesiumView.clock.currentTime,
        cesiumView.clock.startTime
      );
      var heading = Cesium.Math.toRadians(delTime * angle) + initialHeading;
      cesiumView.scene.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(
          cameras.lng,
          cameras.lat,
          40000
        ), // 旋转中心点的坐标
        orientation: {
          heading: heading,
          pitch: pitch,
        },
      });
      cesiumView.scene.camera.moveBackward(distance);
    };
    cesiumView.clock.onTick.addEventListener(Exection);
    var timeinit = 0; //时间累加器
    // 到规定时间后 说明用户没有操作 递归旋转函数
    var timeadd = null;
    // 监听全局鼠标移动
    document.querySelector("html").addEventListener("mousemove", () => {
      //监听移除地图旋转事件
      if (cesiumView && Exection) {
        cesiumView.clock.onTick.removeEventListener(Exection);
      }
      //当鼠标移动 清楚定时器 重新计时
      clearInterval(timeadd);
      timeinit = 0;
      timeadd = setInterval(() => {
        timeinit++;
        if (timeinit >= 10) {
          this.rotateCamera(cesiumView, cameras);
        }
      }, 1000);
    });
  }
  addZheZhao(geojson) {
    let arr = [];
    geojson.features[0].geometry.coordinates[0][0].forEach((item) => {
      arr.push(item[0]);
      arr.push(item[1]);
    });
    var maskspoint = Cesium.Cartesian3.fromDegreesArray(arr);
    var polygonWithHole = new Cesium.PolygonGeometry({
      polygonHierarchy: new Cesium.PolygonHierarchy(
        Cesium.Cartesian3.fromDegreesArray([
          73.0, 53.0, 73.0, 0.0, 135.0, 0.0, 135.0, 53.0,
        ]),
        [new Cesium.PolygonHierarchy(Cesium.Cartesian3.fromDegreesArray(arr))]
      ),
    });

    var geometry = Cesium.PolygonGeometry.createGeometry(polygonWithHole);
    let instances = [];
    instances.push(
      new Cesium.GeometryInstance({
        geometry: geometry,
        attributes: {
          color: Cesium.ColorGeometryInstanceAttribute.fromColor(
            Cesium.Color.fromCssColorString("#1e2426")
          ),
        },
      })
    );
    function addRect(instances, left, down, right, up) {
      instances.push(
        new Cesium.GeometryInstance({
          geometry: new Cesium.RectangleGeometry({
            rectangle: Cesium.Rectangle.fromDegrees(left, down, right, up),
          }),
          attributes: {
            color: Cesium.ColorGeometryInstanceAttribute.fromColor(
              Cesium.Color.fromCssColorString("#1e2426")
            ),
          },
        })
      );
    }
    addRect(instances, -180.0, -90.0, 73.0, 90.0);
    addRect(instances, 135.0, -90.0, 180.0, 90.0);
    addRect(instances, 73.0, 53.0, 135.0, 90.0);
    addRect(instances, 73.0, -90.0, 135.0, 0.0);
    this.viewer.scene.primitives.add(
      new Cesium.Primitive({
        geometryInstances: instances,
        appearance: new Cesium.PerInstanceColorAppearance({
          flat: true,
          translucent: false,
        }),
      })
    );
    const entity3 = new Cesium.Entity({
      name: "动态立体墙",
      wall: {
        positions: maskspoint,
        maximumHeights: maskspoint.map((res) => {
          // return 600;
          return 400;
        }),
        minimumHeights: maskspoint.map((res) => {
          return -600;
        }),
        material: Cesium.Color.fromCssColorString("##2a373c"),
      },
    });
    this.viewer.entities.add(entity3);
  }

  //data就是geojson数据
  AddWaterLayer(data) {
    Cesium.Math.setRandomNumberSeed(0);
    let promise = Cesium.GeoJsonDataSource.load(data);
    let highlightedEntity;
    var highlightColor = Cesium.Color.GREEN.withAlpha(0.6);
    var normalColor = Cesium.Color.YELLOW.withAlpha(0.6);
    function createCallback(entity) {
      const colorProperty = new Cesium.CallbackProperty(function (
        time,
        result
      ) {
        if (highlightedEntity === entity) {
          return Cesium.Color.clone(highlightColor, result);
        }
        return Cesium.Color.clone(normalColor, result);
      },
      false);
      // if (highlightedEntity === entity) {
      //   return new Cesium.ColorMaterialProperty(colorProperty);
      // } else {
      //   return new Cesium.ImageMaterialProperty({
      //     image:
      //       "https://aplid-51.oss-cn-hangzhou.aliyuncs.com/1718940162942_94e32e29.png",
      //   });
      // }
      return new Cesium.ImageMaterialProperty({
        image:
          "https://aplid-51.oss-cn-hangzhou.aliyuncs.com/1718940162942_94e32e29.png",
      });
    }

    promise.then((dataSources) => {
      this.viewer.dataSources.add(dataSources);
      // 获取datasources中的实体
      let entities = dataSources.entities.values;
      //获取每一个实体
      entities.forEach((entity, i) => {
        //设置随机颜色
        entity.polygon.material = createCallback(entity);
        entity.polygon.perPositionHeight = true;
        entity.polygon.fill = true;
        entity.polygon.outline = true;
        entity.polygon.outlineWidth = 20;
        entity.polygon.outlineColor = Cesium.Color.fromCssColorString("#fff");
        //挤出高度
        entity.polygon.height = 200000.0; //离地高度;
        entity.polygon.extrudedHeight = 600;
        this.viewer.zoomTo(promise);
      });
    });

    // let aroundPoint = new AroundPoint(
    //   this.viewer,
    //   0.2,
    //   new Cesium.Cartesian3.fromDegrees(118.796624, 32.059344,60000),
    //   1000.0
    // );

    // aroundPoint.start();

    const handler = new Cesium.ScreenSpaceEventHandler(
      this.viewer.scene.canvas
    );
    handler.setInputAction((movement) => {
      let pickedObject = this.viewer.scene.pick(movement.endPosition);
      if (
        Cesium.defined(pickedObject) &&
        pickedObject.id instanceof Cesium.Entity
      ) {
        highlightedEntity = pickedObject.id;
      } else {
        highlightedEntity = undefined;
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE); //MOUSE_MOVE  LEFT_CLICK
  }

  async addGeoGesion() {
    // 加载河流
    this.AddWaterLayer(`${baseUrl}/apld-tiles/stream.json`);
  }
  addMarkers(markerList: any[], iconWidth?: number, iconHeight?: number) {
    const entityList = markerList.map((item) => {
      const lnglat = item.lnglat.split(",");
      let tempObj: any = {
        position: Cesium.Cartesian3.fromDegrees(lnglat[0], lnglat[1], 0),
        billboard: {
          image: item.icon,
          width: iconWidth || 60,
          height: iconHeight || 80,
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
          eyeOffset: new Cesium.Cartesian3(0, 0, -500),
        },
        label: {},
        data: item,
      };
      if (item.showLabel) {
        tempObj.label = {
          text: item.name,
          font: "31px sans-serif",
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BASELINE,
          fillColor: Cesium.Color.WHILE,
          showBackground: true,
          backgroundColor: new Cesium.Color(1, 1, 1, 0),
          backgroundPadding: new Cesium.Cartesian2(8, 4),
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
          pixelOffset: new Cesium.Cartesian2(2, 75),
        };
      }

      const entity = this.viewer.entities.add(tempObj);
      return entity;
    });
    const handler = new Cesium.ScreenSpaceEventHandler(
      this.viewer.scene.canvas
    );
    handler.setInputAction((e) => {
      const pick = this.viewer.scene.pick(e.position);
      if (pick && pick.id) {
        const markerItem = pick.id._data;
        setMarkerItem(markerItem);
        setMarkerVisible(true);
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    this.viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(118.769943, 32.066814, 8000),
    });
    // this.viewer.flyTo(entityList, {
    // 	duration: 1, // 以秒为单位的飞行持续时间。
    // 	maximumHeight: 2000, // 飞行高峰时（切换视角时）的最大高度。
    // 	offset: {
    // 		heading: Cesium.Math.toRadians(0.0), // 以弧度为单位的航向角。
    // 		pitch: Cesium.Math.toRadians(-90), // 以弧度为单位的俯仰角。
    // 		range: 1000, // 到中心的距离，以米为单位。
    // 	},
    // }) //居中到该点
  }
  addKml() {
    this.viewer.dataSources.add(Cesium.KmlDataSource.load("/data/gulou.kml"));
  }
}

export default Controller;
